/*
 * Flashlib - QB9 common Flash library
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */


package com.qb9.flashlib.profiling
{
	import flash.events.Event;
	import flash.utils.getTimer;

	/**
	 * Simple text field that shows the Flash Player framerate.
	 */
	public class FPSMeter extends Meter
	{
		private var counter:uint;
		private var last:int;

		private var refreshInterval:uint;

		/**
		 * Creates (autostarts and autopositions) an FPSMeter
		 */
		public function FPSMeter(refreshInterval:uint=1000, x:Number = -60, y:Number = 10)
		{
			super(x, y);

			this.refreshInterval = refreshInterval;
			
			init();
		}
		
		private function init():void
		{
			addEventListener(Event.ENTER_FRAME, count);
			reset();
			setText(0);
		}
		
		private function reset():void
		{
			counter = 0;
			last = getTimer();
		}
		
		private function count(e:Event):void
		{
			counter++;
			
			var elapsed:int = getTimer() - last;
			if (elapsed >= refreshInterval)
			{
				var ratio:Number = 1000 / elapsed;
				setText(counter * ratio);
				reset();
			}
		}
		
		private function setText(fps:Number):void
		{
			text = fps.toFixed(1) + ' fps';
		}
		
		override public function dispose():void
		{
			removeEventListener(Event.ENTER_FRAME, count);
			super.dispose();
		}
	}
}
